package main

import "net"

type User struct {
	Name string
	Addr string
	C chan string
	conn net.Conn
	server *Server
}

func (user *User) ListenMessage()  {
	for {
		msg:=<-user.C
		//msg = "\n" + msg
		user.conn.Write([]byte(msg))
	}
}

func NewUser(conn net.Conn,server *Server) *User{
	userAddr:=conn.RemoteAddr().String()
	user:=&User{
		Name: userAddr,
		Addr: userAddr,
		C: make(chan string),
		conn: conn,
		server: server,
	}
	go user.ListenMessage()
	return user
}
func (user *User) Online()  {

	user.server.mapLock.Lock()
	user.server.OnlineMap[user.Name] = user
	user.server.mapLock.Unlock()
	user.server.BoradCast(user,"online")
}
func (user *User) Offline(){

	user.server.mapLock.Lock()
	delete(user.server.OnlineMap, user.Name)
	user.server.mapLock.Unlock()
	user.server.BoradCast(user,"offline")
}
func (user *User) DoMessage(msg string)  {


	if msg=="who" {
		user.server.mapLock.Lock()
		for _,u:=range user.server.OnlineMap{

			onlineMsg:= "["+u.Addr+"]"+ u.Name +":"+"online..."
			user.SendMessage(onlineMsg)
		}
		user.server.mapLock.Unlock()
	} else {
		user.server.BoradCast(user,msg)
	}
	
}
func (user *User) SendMessage(msg string){

	user.conn.Write([]byte(msg))
}